<template>
  <div class="report-form">
    <!-- 表单：填写报工日期、时间范围、工作内容、交付物描述 -->
    <el-form ref="reportForm" :model="reportData" label-width="120px" class="form-container">
      <!-- 报工日期 -->
      <el-form-item label="报工日期">
        <el-date-picker
          v-model="reportData.workDate"
          type="date"
          placeholder="请选择报工日期"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
        />
      </el-form-item>

      <!-- 快捷操作：新增报工、导入Excel、下载模板 -->
      <div class="quick-actions">
        <el-button type="primary" @click="handleCreateReport">新增报工</el-button>
        <el-button type="success" @click="handleImport">导入报工(Excel)</el-button>
        <el-button type="warning" @click="handleDownloadTemplate">下载模板</el-button>
      </div>

      <!-- 时间范围选择 -->
      <el-form-item label="时间范围">
        <div class="time-range-container">
          <div class="time-range">
            <!-- 开始时间 -->
            <el-time-select
              v-model="reportData.startTime"
              placeholder="开始时间"
              :picker-options="timeOptions"
            />
            <span class="time-separator">-</span>
            <!-- 结束时间 -->
            <el-time-select
              v-model="reportData.endTime"
              placeholder="结束时间"
              :picker-options="timeOptions"
            />
          </div>
          <!-- 快捷按钮(上午/下午) -->
          <div class="quick-time-buttons">
            <el-button size="small" @click="setQuickRange('morning')">08:30-12:00</el-button>
            <el-button size="small" @click="setQuickRange('afternoon')">13:30-18:00</el-button>
          </div>
        </div>
      </el-form-item>

      <!-- 工作内容文本 -->
      <el-form-item label="工作内容">
        <el-input
          type="textarea"
          v-model="reportData.workContent"
          placeholder="请输入工作内容"
        />
      </el-form-item>

      <!-- 交付物文本 + 上传附件 -->
      <el-form-item label="交付物">
        <div class="deliverables">
          <!-- deliverables是描述性文本 -->
          <el-input
            type="textarea"
            v-model="reportData.deliverables"
            placeholder="请输入交付物描述"
          />
          <!-- 上传附件 => 后端返回 { attachmentUrl, attachmentFilename }，仅允许覆盖或设置唯一附件 -->
          <!--<el-upload-->
          <!--  action="/dev-api/reports/upload-deliverables"-->
          <!--  :on-success="onDeliverablesUploadSuccess"-->
          <!--  multiple-->
          <!--  :show-file-list="false"-->
          <!--&gt;-->
          <!--  <el-button type="primary" plain>上传附件</el-button>-->
          <!--</el-upload>-->
          <!-- 按钮打开上传对话框 -->
          <el-button type="primary" @click="openAttachmentDialog">上传附件</el-button>
        </div>
      </el-form-item>

      <!-- “新增/修改” & “重置” 按钮 -->
      <el-form-item>
        <div class="form-actions">
          <el-button type="primary" @click="handleAddOrUpdateWorkItem">
            {{ isEditingWorkItem ? "修改" : "新增" }}
          </el-button>
          <el-button type="warning" @click="resetWorkItemFields">重置</el-button>
        </div>
      </el-form-item>
    </el-form>

    <!-- 工作内容列表 -->
    <div class="work-contents">
      <h4>工作内容列表</h4>
      <el-table :data="reportItems" border stripe class="table-content">
        <!-- 时间范围 -->
        <el-table-column prop="timeRange" label="时间范围" width="180" />
        <!-- 工时 -->
        <el-table-column prop="workHours" label="工时(h)" width="100" />
        <!-- 工作内容文本 -->
        <el-table-column prop="workContent" label="工作内容" />
        <!-- 交付物描述文本 -->
        <el-table-column prop="deliverables" label="交付物描述" />
        <!-- 仅一个附件: 显示 attachmentFilename，若无 => “无” -->
        <el-table-column label="附件">
          <template #default="scope">
            <div v-if="scope.row.attachmentUrl && scope.row.attachmentFilename">
              {{ scope.row.attachmentFilename }}
            </div>
            <div v-else>无</div>
          </template>
        </el-table-column>

        <!-- 修改 / 删除 -->
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button
              size="mini"
              type="primary"
              @click="handleEditWorkItem(scope.row, scope.$index)"
            >
              修改
            </el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDeleteWorkItem(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 草稿、提交 -->
    <div class="actions">
      <el-button type="success" @click="saveDraft">保存草稿</el-button>
      <el-button type="primary" @click="submitReport">提交</el-button>
      <!-- 若不需要取消, 注释掉-->
      <el-button type="danger" @click="cancelReport">取消</el-button>

    </div>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px">
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 上传附件对话框 -->
    <el-dialog :title="attachmentUpload.title" :visible.sync="attachmentUpload.open" width="400px">
      <el-upload
        ref="attachmentUpload"
        :limit="1"
        :headers="attachmentUpload.headers"
        :action="attachmentUpload.url"
        :file-list="attachmentUpload.fileList"
        :on-progress="handleAttachmentUploadProgress"
        :on-success="handleAttachmentUploadSuccess"
        :on-remove="handleAttachmentRemove"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击上传</em>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">
          提示：可上传任何文件格式，上传新的文件将替换之前的文件。
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAttachmentUpload">确 定</el-button>
        <el-button @click="closeAttachmentDialog">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import service from "@/utils/request";
import { getToken } from "@/utils/auth";


/**
 * 每条工作内容只允许1个附件, 后端返回 { attachmentUrl, attachmentFilename }:
 * - 通过 onDeliverablesUploadSuccess(response) 记录到 "编辑态" 的临时字段(attachmentUrl, attachmentFilename).
 * - 新增/修改时，如果有 attachmentUrl => workItem.attachmentUrl= that, workItem.attachmentFilename= that;
 * - 若无 => “无”(表格中显示).
 *
 * 最终在表格“附件”列显示 attachmentFilename, 没有则显示“无”.
 */

export default {
  name: "ReportForm",
  data() {
    return {
      // 当前日报基本信息
      reportData: {
        id: null,
        workDate: new Date(),
        startTime: "",
        endTime: "",
        workContent: "",
        deliverables: "",
        attachmentUrl: ""
      },
      // 多条工作内容:
      // each item => {
      //   timeRange, hours, content, deliverables,
      //   attachmentUrl, attachmentFilename
      // }
      reportItems: [],
      // 时间选择器范围
      timeOptions: {
        selectableRange: "08:00:00 - 18:00:00"
      },
      // 是否编辑工作内容
      isEditingWorkItem: false,
      // 正在编辑的workItem索引
      editingIndex: null,

      // 临时存放“已上传”但未写进workItem的 附件信息
      attachmentUrl: "",
      attachmentFilename: "",
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/reports/upload-excel",
      },
      // 附件上传对话框数据
      attachmentUpload: {
        open: false,
        title: "上传附件",
        isUploading: false,
        headers: { Authorization: "Bearer " + getToken() },
        url: process.env.VUE_APP_BASE_API + "/reports/upload-deliverables",
        fileList: [], // 已上传的文件信息
      },
    };
  },
  computed: {
    // 判断是否编辑模式
    isEditPage() {
      return this.$route.path.startsWith("/report/edit");
    }
  },
  mounted() {
    // 如果是编辑模式, 加载已有日报
    if (this.isEditPage) {
      this.loadDailyReport();
    }
  },
  methods: {
    /**
     * 加载单条日报
     * GET /reports/getone/:id
     */
    async loadDailyReport() {
      const { id } = this.$route.params;
      if (!id) return;
      try {
        const { data } = await service.get(`/reports/getone/${id}`);
        console.log(data);
        this.reportData.id = data.data.id;
        this.reportData.workDate = data.data.workDate;
        // 后端返回的 workContent
        this.reportItems = data.data.reportItems || [];
      } catch (err) {
        this.$message.error("加载日报详情失败");
      }
    },

    /**
     * 新增报工 => 跳转到新增报工页面
     */
    handleCreateReport() {
      this.$confirm("确定要新增空白日报吗？未保存的内容将丢失", "提示")
        .then(() => {
          // 跳转到新增页面
          this.$router.push("/report/new");
        })
        .catch(() => {
          // 如果用户取消，则不进行操作
          this.$message.info("已取消新增报工");
        });
    },

    /**
     * 设置上午/下午时间
     */
    setQuickRange(type) {
      if (type === "morning") {
        this.reportData.startTime = "08:30";
        this.reportData.endTime = "12:00";
      } else {
        this.reportData.startTime = "13:30";
        this.reportData.endTime = "18:00";
      }
    },

    /**
     * 新增/修改工作内容
     * 若 this.attachmentUrl => item.attachmentUrl = that, item.attachmentFilename = that
     * 否则 => null
     */
    handleAddOrUpdateWorkItem() {
      debugger
      // 简单校验
      if (!this.reportData.startTime || !this.reportData.endTime || !this.reportData.workContent) {
        this.$message.error("请填写时间范围和工作内容后再点击新增/修改");
        return;
      }
      // 组装workItem
      const item = {
        timeRange: `${this.reportData.startTime} - ${this.reportData.endTime}`,
        workHours: this.calculateHours(this.reportData.startTime, this.reportData.endTime),
        workContent: this.reportData.workContent,
        deliverables: this.reportData.deliverables,
        attachmentUrl: this.attachmentUrl || null,
        attachmentFilename: this.attachmentFilename || null
      };

      if (this.isEditingWorkItem) {
        // 修改
        this.$set(this.reportItems, this.editingIndex, item);
        this.$message.success("工作内容修改成功");
        this.isEditingWorkItem = false;
        this.editingIndex = null;
      } else {
        // 新增
        this.reportItems.push(item);
        this.$message.success("工作内容新增成功");
      }

      // 重置输入
      this.resetWorkItemFields();
    },

    /**
     * 重置输入区
     */
    resetWorkItemFields() {
      this.reportData.startTime = "";
      this.reportData.endTime = "";
      this.reportData.workContent = "";
      this.reportData.deliverables = "";
      this.attachmentUrl = "";
      this.attachmentFilename = "";
      this.isEditingWorkItem = false;
      this.editingIndex = null;
    },

    /**
     * 编辑 => 回填到输入区
     */
    handleEditWorkItem(row, index) {
      if (!row.timeRange || !row.timeRange.includes("-")) {
        this.$message.error("时间范围格式错误，请检查数据！");
        return;
      }

      // 分割时直接按 "-" 分隔，并去掉多余空格
      const [start, end] = row.timeRange.split("-").map(time => time.trim());

      // console.log(start, end); // 确认分割结果
      this.reportData.startTime = start;
      this.reportData.endTime = end;
      this.reportData.workContent = row.workContent;
      this.reportData.deliverables = row.deliverables;
      this.attachmentUrl = row.attachmentUrl || "";
      this.attachmentFilename = row.attachmentFilename || "";

      this.isEditingWorkItem = true;
      this.editingIndex = index;
    },

    /**
     * 取消按钮，返回列表页面
     */
    cancelReport() {
      this.$confirm(
        '当前页面的内容未保存，确定要返回列表页面吗？所有未保存的更改将丢失！',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          // 用户确认取消，跳转到列表页面
          this.$router.push("/report/list");
          this.$message.success('已返回列表页面');
        })
        .catch(() => {
          // 用户取消操作
          this.$message.info('已取消操作');
        });
    },

    /**
     * 删除 reportItems 里的内容
     */
    handleDeleteWorkItem(row) {
      this.$confirm(
        '确定要删除这条工作内容吗？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          // 用户确认删除
          const idx = this.reportItems.indexOf(row);
          if (idx > -1) {
            this.reportItems.splice(idx, 1);
            this.$message.success('工作内容删除成功');
          }
        })
        .catch(() => {
          // 用户取消删除
          this.$message.info('已取消删除');
        });
    },

    /**
     * 保存草稿 => status="草稿"
     */
    async saveDraft() {
      const payload = {
        id: this.reportData.id,
        workDate: this.reportData.workDate,
        status: "0",
        reportItems: this.reportItems
      };
      try {
        if (payload.id) {
          // 编辑
          await service.put(`/reports/edit/${payload.id}`, payload);
        } else {
          // 新增
          const res = await service.post("/reports/add", payload);
          if (res.data?.id) {
            this.reportData.id = res.data.id;
          }
        }
        this.$message.success("草稿已保存");
      } catch (err) {
        this.$message.error("草稿保存失败");
      }
    },

    /**
     * 提交 => status="已提交"
     */
    async submitReport() {
      if (!this.reportItems.length) {
        this.$message.error("请至少新增一条工作内容后再提交");
        return;
      }
      const payload = {
        id: this.reportData.id,
        workDate: this.reportData.workDate,
        status: "1",
        reportItems: this.reportItems
      };
      try {
        if (payload.id) {
          await service.put(`/reports/edit/${payload.id}`, payload);
        } else {
          await service.post("/reports/add", payload);
        }
        this.$message.success("日报已提交");
        await this.$router.push("/report/list");
      } catch (err) {
        this.$message.error("提交失败");
      }
    },

    /**
     * 上传附件成功 => 覆盖, 只1个
     * 仅在“编辑态”或“新增态”下使用
     */
    onDeliverablesUploadSuccess(response) {
      // 后端返回 { attachmentUrl, attachmentFilename }
      if (response.code === 200) {
        console.log(response);
        this.attachmentUrl = response.data.url;
        this.attachmentFilename = response.data.fileName || "未知文件名";
        this.$message.success("附件上传成功, 已记录");
      }
    },

    /**
     * 下载模板 => /reports/importTemplate
     */
    handleDownloadTemplate() {
      this.download('/reports/importTemplate',
        {},
        `reports_${new Date().getTime()}.xlsx`)
    },

    /**
     * 计算工时(如08:30->12:00 =>3.5h)
     */
    calculateHours(startTime, endTime) {
      const start = new Date(`1970-01-01T${startTime}:00`);
      const end = new Date(`1970-01-01T${endTime}:00`);
      const diff = (end - start) / (1000 * 60 * 60);
      return diff > 0 ? diff : 0;
    },

    /**
     * Excel导入导出操作
     */
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "Excel文档导入";
      this.upload.open = true;
    },

    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;  // 关闭上传框
      this.upload.isUploading = false;  // 设置上传状态为不上传
      this.$refs.upload.clearFiles();  // 清除上传文件列表

      // 检查响应是否包含有效的 reportItemList
      if (response.data && Array.isArray(response.data)) {
        // 将导入的报告内容追加到现有的 reportItems 列表
        this.reportItems = this.reportItems.concat(response.data);

        // 弹出成功提示
        this.$message.success("Excel 数据已导入，工作内容列表已更新");
      } else {
        // 如果响应格式不符合预期，给出错误提示
        this.$message.error("导入失败，请检查文件格式");
      }

      // 弹出导入结果的提示框
      // this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },

    /**
     * 上传附件功能
     */
    // 打开附件上传对话框
    openAttachmentDialog() {
      this.attachmentUpload.open = true;

      // 如果已有上传的附件，将其显示在文件列表中
      if (this.attachmentUrl && this.attachmentFilename) {
        this.attachmentUpload.fileList = [
          {
            name: this.attachmentFilename,
            url: this.attachmentUrl,
          },
        ];
      } else {
        this.attachmentUpload.fileList = [];
      }
    },

    // 关闭附件上传对话框
    closeAttachmentDialog() {
      this.attachmentUpload.open = false;
      this.attachmentUpload.isUploading = false;
    },

    // 上传进度处理
    handleAttachmentUploadProgress(event, file, fileList) {
      this.attachmentUpload.isUploading = true;
    },

    // 上传成功处理
    handleAttachmentUploadSuccess(response, file, fileList) {
      if (response.code === 200) {
        // 更新附件信息
        this.attachmentUrl = response.data.url;
        this.attachmentFilename = file.name;
        this.attachmentUpload.fileList = [
          {
            name: file.name,
            url: response.data.url,
          },
        ];
        this.$message.success("附件上传成功，已替换原附件");
      } else {
        this.$message.error("附件上传失败，请重试");
      }
      this.closeAttachmentDialog();
    },

    // 删除附件处理
    handleAttachmentRemove(file, fileList) {
      this.attachmentUrl = ""; // 清空地址
      this.attachmentFilename = ""; // 清空文件名
      this.attachmentUpload.fileList = [];
      this.$message.info("已移除附件");
    },

    // 提交上传
    submitAttachmentUpload() {
      this.$refs.attachmentUpload.submit();
    },
  }
};
</script>

<style lang="scss" scoped>
.report-form {
  padding: 20px;
  background: #f9f9f9;

  .form-container {
    margin-bottom: 20px;
  }

  .quick-actions {
    margin: 0 0 10px 50px;
    display: flex;
    align-items: center;
    gap: 10px;
  }

  .form-actions {
    display: flex;
    align-items: center;
    gap: 10px;
  }

  .time-range-container {
    display: flex;
    align-items: center;
    .time-range {
      display: flex;
      align-items: center;
      padding-right: 10px;
      .time-separator {
        margin: 0 5px;
      }
    }
    .quick-time-buttons {
      display: flex;
      gap: 5px;
    }
  }

  .deliverables {
    display: flex;
    align-items: center;
    gap: 10px;
    el-input {
      width: 80%;
    }
  }

  .work-contents {
    margin-top: 20px;
    .table-content {
      width: 100%;
    }
  }

  .actions {
    margin-top: 20px;
    text-align: center;
    button + button {
      margin-left: 10px;
    }
  }
}
</style>
